﻿'use strict';

angular.module('ishaCrmApp')

    .service('googleAuthSvc', ['$http', '$q', '$cookieStore', function ($http, $q, $cookieStore) {

        this.checkLogin = function () {
            var defCheckLogin = $q.defer();
            gapi.auth.authorize({
                client_id: app.CLIENT_ID,
                scope: app.SCOPES,
                immediate: true
            }, function (authResult) {
                if (authResult && authResult.error) {
                    defCheckLogin.reject(authResult.error);
                } else {
                    defCheckLogin.resolve(authResult);
                }
            });
            return defCheckLogin.promise;
        }

        this.login = function () {

            var defLogin = $q.defer();

            gapi.auth.authorize({
                client_id: app.CLIENT_ID,
                scope: app.SCOPES,
                immediate: false,
                authuser: '' //For Multiple logins, if you set authuser to empty then it will prompt with list of logins to select. But, user has to select the right Google Account twice
            }, function (authResult) {
                if (authResult && authResult.error) {
                    defLogin.reject(authResult.error);
                } else {
                    defLogin.resolve(authResult);
                }
            });

            return defLogin.promise;
        }

        this.userInfo = function () {

            var defUserInfo = $q.defer();

            gapi.client.oauth2.userinfo.get().execute(function (resp) {
                if (resp && resp.code) {
                    defUserInfo.reject(resp.message);
                } else {
                    defUserInfo.resolve(resp);
                }
            });

            return defUserInfo.promise;
        }

    }]);


